#include "audiohandler.h"

AudioHandler::AudioHandler(QString userName, QString ip, quint16 port, QObject *parent)
    : QObject(parent), userName(userName), ip(ip), port(port + 100)
{
    socketAudio = new QUdpSocket(this);
    socketAudio->bind(QHostAddress::AnyIPv4, this->port,
                      QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint);
    socketAudio->joinMulticastGroup(QHostAddress(ip));
    connect(socketAudio, &QUdpSocket::readyRead, this, &AudioHandler::onReadyReadAudio);

    QAudioFormat format;
    format.setSampleRate(8000);
    format.setChannelCount(1);
    format.setSampleSize(16);
    format.setCodec("audio/pcm");
    format.setByteOrder(QAudioFormat::LittleEndian);
    format.setSampleType(QAudioFormat::SignedInt);
    audioInput = new QAudioInput(format, this);
    audioOutput = new QAudioOutput(format, this);
    audioOutputIODevice = audioOutput->start();

    connect(audioInput, &QAudioInput::stateChanged, this, &AudioHandler::onStateChange);
}

void AudioHandler::onCbAudio()
{
    if (audioInput->state() == QAudio::ActiveState)
    {
        audioInput->stop();
        disconnect(audioInputIODevice, &QIODevice::readyRead, this, &AudioHandler::captureDataFromDevice);
    }
    else
    {
        audioInputIODevice = audioInput->start();
        connect(audioInputIODevice, &QIODevice::readyRead, this, &AudioHandler::captureDataFromDevice);
    }
}

void AudioHandler::captureDataFromDevice()
{
    AudioPackage pack;
    memset(&pack, 0, sizeof(AudioPackage));
    strncpy(pack.name, userName.toStdString().c_str(), 64);
    pack.dataLen = audioInputIODevice->read(pack.data, 1024);
    socketAudio->writeDatagram((char *)&pack, sizeof(AudioPackage), QHostAddress(ip), port);
//    audioOutputIODevice->write(pack.data, pack.dataLen);
}

void AudioHandler::onReadyReadAudio()
{
    AudioPackage pack;
    memset(&pack, 0, sizeof(AudioPackage));
    socketAudio->readDatagram((char *)&pack, sizeof(AudioPackage));
    if (strncmp(pack.name, userName.toStdString().c_str(), 64) == 0) return ;
    audioOutputIODevice->write(pack.data, pack.dataLen);
}

void AudioHandler::onStateChange(QAudio::State state)
{
    emit stateChange(state);
}
